Imports System.IO
Public Class FormWriter


    Private Sub Btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn.Click
        Dim FileDB As New SaveFileDialog()

        FileDB.Filter = "All files | *.* | Text files | *.txt"

        FileDB.FilterIndex = 2
        FileDB.InitialDirectory = "C:\"
        FileDB.AddExtension = True
        FileDB.DefaultExt = "txt"

        If (FileDB.ShowDialog() = Windows.Forms.DialogResult.OK) Then
            Dim TargetFile As StreamWriter = Nothing

            Try
                TargetFile = New StreamWriter(FileDB.FileName)
            Catch
                MsgBox("Error opening " & FileDB.FileName)
            End Try

            Try
                TargetFile.Write(TextBox1.Text)
            Catch
                MsgBox("Error writing file")
            End Try

            TargetFile.Close()
            MsgBox("Text saved to " & FileDB.FileName)
        Else
            MsgBox("User selected Cancel")
        End If

    End Sub

    Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click

        Dim FileDB As New OpenFileDialog()

        FileDB.Filter = "All files | *.* | Text files |*.txt"

        FileDB.FilterIndex = 2
        FileDB.InitialDirectory = "C:\"
        FileDB.AddExtension = True
        FileDB.DefaultExt = "txt"

        If (FileDB.ShowDialog() = Windows.Forms.DialogResult.OK) Then
            Dim SourceFile As StreamReader

            Try
                SourceFile = New StreamReader(FileDB.FileName)
            Catch
                MsgBox("Loi " & FileDB.FileName)
            End Try

            Try
                TextBox1.Text = SourceFile.ReadToEnd()
            Catch
                MsgBox("Loi doc file")
            End Try

            SourceFile.Close()
        Else
            MsgBox("Nguoi dung chon Cancel")
        End If

    End Sub

End Class
